from flask import Blueprint, request, jsonify
from models import db, User
from utils.scrypt import generate_salt, encrypt_password
from utils.res import success_response, error_response
from flask import current_app as app
from utils.token_tools import token_required
import jwt

user_bp = Blueprint('user_bp', __name__)

@user_bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify(error_response("用户名和密码不能为空")), 400

    if User.query.filter_by(username=username).first():
        return jsonify(error_response("用户名已存在")), 409

    salt = generate_salt()
    hashed_password = encrypt_password(password, salt)

    new_user = User(username=username, password=hashed_password, salt=salt)
    db.session.add(new_user)
    db.session.commit()

    return jsonify(success_response("注册成功"))


@user_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get("username")
    password = data.get("password")

    if not username or not password:
        return jsonify(error_response("用户名和密码不能为空")), 400

    user = User.query.filter_by(username=username).first()
    if not user:
        return jsonify(error_response("用户不存在")), 404

    from utils.scrypt import encrypt_password
    hashed = encrypt_password(password, user.salt)
    if hashed != user.password:
        return jsonify(error_response("密码错误")), 401

    # 生成 JWT
    token = jwt.encode(
        {"user_id": user.id},
        app.config["JWT_SECRET_KEY"],
        algorithm="HS256"
    )

    return jsonify(success_response("登录成功", {"token": token}))


@user_bp.route('/users', methods=['GET'])
@token_required
def get_users():
    users = User.query.all()
    user_list = [{"id": u.id, "username": u.username} for u in users]
    return jsonify(success_response("用户列表获取成功", user_list))


@user_bp.route('/users/<int:user_id>', methods=['PUT'])
@token_required
def update_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return jsonify(error_response("用户不存在")), 404

    data = request.get_json()
    username = data.get("username")
    password = data.get("password")

    if username:
        user.username = username
    if password:
        from utils.scrypt import generate_salt, encrypt_password
        new_salt = generate_salt()
        user.salt = new_salt
        user.password = encrypt_password(password, new_salt)

    db.session.commit()
    return jsonify(success_response("用户信息更新成功"))


@user_bp.route('/users/<int:user_id>', methods=['DELETE'])
@token_required
def delete_user(user_id):
    user = User.query.get(user_id)
    if not user:
        return jsonify(error_response("用户不存在")), 404

    db.session.delete(user)
    db.session.commit()
    return jsonify(success_response("用户删除成功"))